package api

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"web/app/model"
)

func init() {
	s := g.Server()
	s.BindHandler("/user", createUser)
	s.BindHandler("/findUser", findUser)
	s.BindHandler("/findUserById", findUserById)
	s.BindHandler("/delUser", delUser)
	s.BindHandler("/updateUser", updateUser)
}

type UserInfo struct {
	ID     int    `json:"id"`
	OpenID string `json:"openId"`
	Phone  string `json:"phone"`
}

func createUser(r *ghttp.Request) {
	//userObj := new(UserInfo)
	userObj := UserInfo{1, "154564", "15189805605"}
	//userObjs := convertRequestToModel(userObj)
	err := model.MUser.Create((*model.User)(&userObj))
	if err != nil {
		fmt.Println("创建失败！")
		r.Response.Writeln("创建失败!")
	} else {
		fmt.Println("创建成功！")
		r.Response.Writeln("创建成功!")
	}
}

func updateUser(r *ghttp.Request) {
	userObj := UserInfo{1, "111111111", "111111111111"}
	err := model.MUser.UpdateObjInfo((*model.User)(&userObj))
	if err != nil {
		fmt.Println("更新失败！")
		r.Response.Writeln("更新失败!")
	} else {
		fmt.Println("更新成功！")
		r.Response.Writeln("更新成功!")
	}
}

func findUser(r *ghttp.Request) {
	var u = new(UserInfo)
	model.MUser.FindFirst((*model.User)(u))
	fmt.Printf("%#v\n", u)
	r.Response.Writeln("创建成功!")
}

func findUserById(r *ghttp.Request) {
	//var u = new(UserInfo)
	data, err := model.MUser.FindObjById(1)
	if err != nil {
		r.Response.Writeln("创建失败!")
	} else {
		fmt.Printf("%#v\n", data)
		r.Response.Writeln("创建成功!")
	}
}

func delUser(r *ghttp.Request) {
	//var u = new(UserInfo)
	err := model.MUser.DeleteObj(1)
	if err != nil {
		r.Response.Writeln("删除失败!")
	} else {
		r.Response.Writeln("删除成功!")
	}
}

func convertRequestToModel(request *UserInfo) *model.User {
	return &model.User{
		ID:     request.ID,
		OpenID: request.OpenID,
		Phone:  request.Phone,
	}
}
